package com.siyoumi.app.modules.app_ess.admin;

import com.siyoumi.app.entity.EssFile;
import com.siyoumi.app.entity.EssModule;
import com.siyoumi.app.modules.app_ess.entity.EnumEssFileType;
import com.siyoumi.app.modules.app_ess.service.SvcEssFile;
import com.siyoumi.app.modules.app_ess.service.SvcEssModule;
import com.siyoumi.app.modules.app_ess.vo.VaEssFile;
import com.siyoumi.component.XEnumBase;
import com.siyoumi.component.http.InputData;
import com.siyoumi.controller.AdminApiController;
import com.siyoumi.util.XReturn;
import com.siyoumi.validator.XValidator;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/xadmin/app_fks/app_ess__file__edit")
public class app_ess__file__edit
        extends AdminApiController {

    @GetMapping()
    public XReturn index() {
        String moduleId = input("module_id");
        Map<String, Object> data = new HashMap<>();
        data.put("efile_module_id", moduleId);
        data.put("efile_file_size", 0);
        data.put("efile_order", 0);
        if (isAdminEdit()) {
            EssFile entity = SvcEssFile.getApp().loadEntity(getID());

            HashMap<String, Object> dataAppend = new LinkedHashMap<>();
            dataAppend.put("id", entity.getKey());
            //
            //合并
            data = entity.toMap();
            data.putAll(dataAppend);

            moduleId = entity.getEfile_module_id();
        }
        getR().setData("data", data);

        //模块
        EssModule entityModule = SvcEssModule.getApp().loadEntity(moduleId);
        setPageTitle(entityModule.getEmod_name(), "-文件添加");

        //数据分类
        EnumEssFileType enumFileType = XEnumBase.of(EnumEssFileType.class);
        setPageInfo("enum_file_type", enumFileType);
        setPageInfo("file_accept", SvcEssFile.fileAccept().stream().collect(Collectors.joining(","))); //允许上传的文件格式

        return getR();
    }


    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/save")
    public XReturn save(@Validated() VaEssFile vo, BindingResult result) {
        //统一验证
        XValidator.getResult(result);
        //
        vo.setEfile_acc_id(getAccId());
        //
        InputData inputData = InputData.fromRequest();
        return SvcEssFile.getBean().edit(inputData, vo);
    }
}
